package cn.tsvtc.shop.service.impl;

import cn.hutool.core.convert.Convert;
import cn.tsvtc.shop.entity.CartItemVO;
import cn.tsvtc.shop.mapper.OrderMapper;
import cn.tsvtc.shop.mapper.ProductMapper;
import cn.tsvtc.shop.pojo.Order;
import cn.tsvtc.shop.pojo.Product;
import cn.tsvtc.shop.service.OrderService;
import cn.tsvtc.shop.utils.IdWorkerUtils;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author: Athena
 * @date: 2020/11/6 15:38
 * @description:
 */
@Service
public class OrderServiceImpl implements OrderService {

    private OrderMapper orderMapper;

    private ProductMapper productMapper;

    public OrderServiceImpl(OrderMapper orderMapper,ProductMapper productMapper){
        this.orderMapper=orderMapper;
        this.productMapper=productMapper;
    }

    /**
     * 添加订单
     *
     * @param cartItemVOList
     * @return
     */
    @Override
    public Order addOrder(List<CartItemVO> cartItemVOList, Long userId) {
        //获取商品总数
        int size = cartItemVOList.size();
        //获取商品的id以及数量
        Map<Product,Long> products=new HashMap<>();
        if(size>0){
            double sum=0;
            for (CartItemVO cartItemVO : cartItemVOList) {
                //获取商品数量

                Long id = cartItemVO.getProduct().getId();
                //添加到map
                products.put(cartItemVO.getProduct(),id);
                //价格累加
                sum+=(cartItemVO.getProduct().getPrice()*cartItemVO.getNum());
            }


            Order order=new Order();
            //生成雪花id
            IdWorkerUtils idWorkerUtils = new IdWorkerUtils();
            long snowId = idWorkerUtils.nextId();
            String temp=Convert.toStr(snowId);
            String substring = temp.substring(1, 16);
            snowId=Convert.toLong(substring);
            //设置雪花id
            order.setId(snowId);
            //设置账户
            order.setAccount(Convert.toStr(userId));
            //设置价格
            order.setAmount(new BigDecimal(sum));
            //订单暂不设置其他
            int insert = orderMapper.insert(order);
            return order;
        }else {
            return null;
        }
    }

    /**
     * 获取订单
     *
     * @param id
     * @return
     */
    @Override
    public Order getOrder(Long id) {
        Order order = orderMapper.selectByPrimaryKey(id);
        return order;
    }
}
